import { BrowserWindow, screen, shell, app } from 'electron';
import path from 'path';
import { fileURLToPath } from 'url';
import { existsSync } from 'fs';
import { isDev } from '../utils/env.js';

// 在ES模块中获取__dirname的等效方式
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 获取图标路径
function getIconPath() {
  // 尝试多个可能的图标路径
  const possiblePaths = [
    path.join(__dirname, '../../public/weblogo.png'),
    path.join(__dirname, '../../../public/weblogo.png'),
    path.join(process.resourcesPath, 'app/public/weblogo.png'),
    path.join(process.cwd(), 'public/weblogo.png')
  ];
  
  // 返回第一个存在的路径
  for (const iconPath of possiblePaths) {
    if (existsSync(iconPath)) {
      return iconPath;
    }
  }
  
  // 如果都不存在，返回默认路径
  return possiblePaths[0];
}

// 创建主窗口
export async function createMainWindow() {
  // 获取屏幕工作区域大小（排除任务栏）
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  
  console.log('Creating window with size:', width, height);
  
  // 创建浏览器窗口
  const mainWindow = new BrowserWindow({
    width: Math.floor(width * 0.9),
    height: Math.floor(height * 0.9),
    minWidth: 800,
    minHeight: 600,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      enableRemoteModule: false,
      preload: path.join(__dirname, '../preload/index.js'),
      webSecurity: !isDev, // 在生产环境中启用webSecurity
      allowRunningInsecureContent: true,
      experimentalFeatures: true,
      plugins: true,
      spellcheck: false,
      autoplayPolicy: 'no-user-gesture-required',
      backgroundThrottling: false,
      offscreen: false
    },
    // 修复图标路径问题
    icon: getIconPath(),
    show: true, // 直接显示窗口，而不是等待ready-to-show事件
    autoHideMenuBar: true, // 自动隐藏菜单栏
    titleBarStyle: process.platform === 'darwin' ? 'hiddenInset' : 'default'
  });
  
  console.log('Window created successfully');

  // 加载应用
  await loadApp(mainWindow);

  // 直接显示窗口，不等待ready-to-show事件
  console.log('Showing window immediately after loading');
  mainWindow.show();
  mainWindow.focus();
  mainWindow.setAlwaysOnTop(true); // 将窗口设置为始终置顶
  mainWindow.restore(); // 确保窗口不是最小化状态
  mainWindow.center(); // 将窗口居中显示
  console.log('Window visibility after show:', mainWindow.isVisible());
  console.log('Window is minimized:', mainWindow.isMinimized());
  console.log('Window is focused:', mainWindow.isFocused());
  
  // 窗口准备好后再次确保聚焦
  mainWindow.once('ready-to-show', () => {
    console.log('Window ready to show event fired');
    console.log('Window visibility:', mainWindow.isVisible());
    mainWindow.show();
    mainWindow.focus();
    mainWindow.restore(); // 确保窗口不是最小化状态
    mainWindow.center(); // 将窗口居中显示
    console.log('Window focused');
  });
  
  // 添加超时机制，确保窗口聚焦
  setTimeout(() => {
    console.log('Timeout check - Window visibility:', mainWindow.isVisible());
    console.log('Window is minimized:', mainWindow.isMinimized());
    console.log('Window is focused:', mainWindow.isFocused());
    
    // 强制显示窗口
    mainWindow.show();
    mainWindow.focus();
    mainWindow.restore(); // 确保窗口不是最小化状态
    mainWindow.center(); // 将窗口居中显示
    mainWindow.setAlwaysOnTop(false); // 取消置顶
    
    console.log('Window forced to show');
  }, 3000); // 3秒后检查
  
  // 监听加载完成事件
  mainWindow.webContents.on('did-finish-load', () => {
    console.log('Window finished loading');
  });
  
  // 监听加载失败事件
  mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
    console.error('Window failed to load:', errorCode, errorDescription, validatedURL);
  });

  // 处理外部链接
  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    shell.openExternal(url);
    return { action: 'deny' };
  });

  // 窗口关闭事件
  mainWindow.on('closed', () => {
    console.log('Window closed');
    // 清理资源
  });

  return mainWindow;
}

// 加载应用内容
async function loadApp(window) {
  try {
    if (isDev) {
      // 开发环境加载Vite服务器
      await window.loadURL('http://localhost:5173');
      
      // 在开发模式下打开开发者工具
      window.webContents.once('did-finish-load', () => {
        setTimeout(() => {
          if (window && !window.webContents.isDevToolsOpened()) {
            window.webContents.openDevTools({ mode: 'detach', activate: true });
          }
        }, 1000);
      });
    } else {
      // 生产环境加载本地文件
      // 使用不同的路径尝试策略
      let indexPath = path.join(__dirname, '../../dist/index.html');
      console.log('Trying path 1:', indexPath);
      
      // 如果第一个路径不存在，尝试其他可能的路径
      if (!existsSync(indexPath)) {
        indexPath = path.join(process.resourcesPath, 'app/dist/index.html');
        console.log('Trying path 2:', indexPath);
      }
      
      if (!existsSync(indexPath)) {
        indexPath = path.join(process.cwd(), 'dist/index.html');
        console.log('Trying path 3:', indexPath);
      }
      
      if (!existsSync(indexPath)) {
        indexPath = path.join(app.getAppPath(), 'dist/index.html');
        console.log('Trying path 4:', indexPath);
      }
      
      console.log('Loading index.html from:', indexPath);
      
      try {
        await window.loadFile(indexPath);
      } catch (error) {
        console.error('Failed to load index.html:', error);
        
        // 如果所有路径都失败，显示错误页面
        await showErrorPage(window, error);
      }
    }
  } catch (error) {
    console.error('Failed to load app:', error);
    
    // 显示错误页面
    await showErrorPage(window, error);
  }
}

// 显示错误页面
async function showErrorPage(window, error) {
  const errorHtml = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>应用加载错误</title>
      <style>
        body {
          font-family: Arial, sans-serif;
          padding: 20px;
          background-color: #f5f5f5;
        }
        .error-container {
          max-width: 800px;
          margin: 0 auto;
          background-color: white;
          padding: 20px;
          border-radius: 8px;
          box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
          color: #e74c3c;
        }
        .error-message {
          background-color: #f8d7da;
          padding: 10px;
          border-radius: 4px;
          margin: 10px 0;
        }
      </style>
    </head>
    <body>
      <div class="error-container">
        <h1>应用加载失败</h1>
        <p>抱歉，应用启动时遇到了问题。</p>
        <div class="error-message">
          <strong>错误信息:</strong> ${error.message || '未知错误'}
        </div>
        <p>请尝试重新启动应用，或联系技术支持。</p>
      </div>
    </body>
    </html>
  `;
  
  await window.loadURL('data:text/html;charset=UTF-8,' + encodeURIComponent(errorHtml));
}